package com.ruoyi.project.downfile.controller;

import java.io.*;
import java.net.URLEncoder;
import java.util.List;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.project.downfile.service.IDownFileService;
import com.ruoyi.project.info.domain.FileInfo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 文件信息Controller
 * 
 * @author ruoyi
 * @date 2019-11-04
 */
@Controller
@RequestMapping("/downfile")
public class DownFileController extends BaseController
{
    private String prefix = "downfile";

    @Autowired
    private IDownFileService downFileService;

//    @RequiresPermissions("downfile:view")
    @GetMapping()
    public String downfile()
    {
        return prefix + "/downfile";
    }

    /**
     * 查询文件信息列表
     */
//    @RequiresPermissions("downfile:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(FileInfo fileInfo)
    {
        startPage();
        List<FileInfo> list = downFileService.selectFileInfoList(fileInfo);
        return getDataTable(list);
    }

    /**
     * 导出文件信息列表
     */
    @RequiresPermissions("downfile:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(FileInfo fileInfo)
    {
        List<FileInfo> list = downFileService.selectFileInfoList(fileInfo);
        ExcelUtil<FileInfo> util = new ExcelUtil<FileInfo>(FileInfo.class);
        return util.exportExcel(list, "info");
    }

    /**
     * 新增文件信息
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存文件信息
     */
    @RequiresPermissions("downfile:add")
    @Log(title = "文件信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(FileInfo fileInfo)
    {
        return toAjax(downFileService.insertFileInfo(fileInfo));
    }

    /**
     * 修改文件信息
     */
    @GetMapping("/edit/{fileId}")
    public String edit(@PathVariable("fileId") Long fileId, ModelMap mmap)
    {
        FileInfo fileInfo = downFileService.selectFileInfoById(fileId);
        mmap.put("fileInfo", fileInfo);
        return prefix + "/edit";
    }

    /**
     * 修改保存文件信息
     */
    @RequiresPermissions("downfile:edit")
    @Log(title = "文件信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(FileInfo fileInfo)
    {
        return toAjax(downFileService.updateFileInfo(fileInfo));
    }

    /**
     * 删除文件信息
     */
    @RequiresPermissions("downfile:remove")
    @Log(title = "文件信息", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(downFileService.deleteFileInfoByIds(ids));
    }

//    /**
//     * 本地资源通用下载
//     */
//    @GetMapping("/common/download/resource")
//    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
//            throws Exception
//    {
//        // 本地资源路径
//        String localPath = Global.getProfile();
//        // 数据库资源地址
//        String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
//        // 下载名称
//        String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
//        response.setCharacterEncoding("utf-8");
//        response.setContentType("multipart/form-data");
//        response.setHeader("Content-Disposition",
//                "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, downloadName));
//        FileUtils.writeBytes(downloadPath, response.getOutputStream());
//    }

    @GetMapping("/download")
    public String download()
    {
        return prefix + "/download";
    }

@RequestMapping(value = {"downfile/download"},method = RequestMethod.GET)
public void download(@RequestParam("filename") String filename, HttpServletRequest request,HttpServletResponse response) throws IOException {
    if(!StringUtils.isEmpty(filename)) {
        //模拟文件，myfile.txt为需要下载的文件
        String path = "D:\\ruoyi\\uploadpath"+"\\"+filename;
        //创建添加定义获取文件
        File file=new File(path);
        //创建添加定义获取该文件的文件输入流
        FileInputStream fileInputStream=new FileInputStream(file);
        //创建添加定义将文件输入流放在输入流里
        InputStream inputStream=new BufferedInputStream(fileInputStream);
        //创建添加定义转码防止文件名中文乱码
        filename=URLEncoder.encode(filename,"UTF-8");
        //创建添加定义设置文件下载头
        response.setHeader("Content-Disposition", "attachment;filename=" + filename);
        //创建添加定义设置下载文件类型
        response.setContentType("multipart/form-data");
        //创建添加定义获取文件输出流
        BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(response.getOutputStream());
        int len=0;
        while((len = inputStream.read()) != -1){
            bufferedOutputStream.write(len);
            bufferedOutputStream.flush();
        }
        bufferedOutputStream.close();
    }

}




}
